<template>
  <div class="app-container" ref="container">
    <!-- 固定的搜索和工具栏容器 -->
    <div class="fixed-header">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="小说名字">
            <el-input v-model="formInline.name" placeholder="小说名字"></el-input>
          </el-form-item>
          <el-form-item label="小说状态">
            <el-select v-model="formInline.serialize" placeholder="全部" clearable>
              <el-option label="连载" value="1"></el-option>
              <el-option label="完结" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上线状态">
            <el-select v-model="formInline.online" placeholder="全部" clearable>
              <el-option label="上线" value="1"></el-option>
              <el-option label="下线" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查 询</el-button>
            <el-button @click="resetQuery">重 置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar-right">
        <el-button type="primary" size="small" @click="handleAdd">
          <i class="el-icon-plus"></i> 新增小说
        </el-button>
        <el-button size="small" @click="handleRefresh">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
    </div>

    <!-- 表格内容区域 -->
    <div class="table-container">
      <!-- 表格和分页容器 -->
      <div class="content-container">
        <el-table
            ref="table"
            v-loading="loading"
            :data="novelList"
            border
            style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="url" label="封面" width="100">
            <template slot-scope="scope">
              <img :src="scope.row.url" alt="" style="width: 50px;height: 50px"></img>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="小说名字" min-width="200">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="serialize" label="小说状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.serialize === 1 ? 'success' : 'danger'">
                {{ scope.row.serialize === 1 ? '连载' : '完结' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="online" label="上线状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.online === 1 ? 'success' : 'danger'">
                {{ scope.row.online === 1 ? '上线' : '下线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ynvip" label="付费模式" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.ynvip === 1 ? 'success' : 'danger'">
                {{ scope.row.ynvip === 1 ? 'VIP模式' : '广告模式' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="pname" label="小说作者" width="120"></el-table-column>
          <el-table-column prop="createtime" label="创建时间" width="180"></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                  size="mini"
                  type="text"
                  @click="handleDelete(scope.row)"
              >删除</el-button>
              <el-button
                  size="mini"
                  type="text"
                  v-if="scope.row.online === 2"
                  @click="handleOnline(scope.row)"
              >上线</el-button>
              <el-button
                  size="mini"
                  type="text"
                  v-if="scope.row.online === 1"
                  @click="handleOffline(scope.row)"
              >下线</el-button>

              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-button
                      size="mini"
                      type="text"
                      @click="handleChapter(scope.row)"
                  >章节列表</el-button>
                  <el-button
                      size="mini"
                      type="text"
                      @click="handleComment(scope.row)"
                  >评论列表</el-button>
                  <el-button
                      size="mini"
                      type="text"
                      @click="Contentsbook(scope.row)"
                  >下载小说</el-button>
                </el-dropdown-menu>
              </el-dropdown>
            </template>


          </el-table-column>
        </el-table>

        <!-- 新增和修改 -->
        <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改小说':'新增小说'">
          <el-form :model="form" :rules="rules" ref="form" label-width="80px">
            <el-form-item label="小说名字" prop="name">
              <el-input v-model="form.name" placeholder="小说名字"></el-input>
            </el-form-item>
            <el-form-item label="小说作者" prop="pname">
              <el-input v-model="form.pname" placeholder="小说作者"></el-input>
            </el-form-item>
            <el-form-item label="小说封面" prop="url">
              <el-upload
                  class="avatar-uploader"
                  action="http://localhost:9999/api-novel/oss/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                <img v-if="form.url" :src="form.url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="upload-tip" v-if="dialogType === 'edit'">不上传则保留原图片</div>
            </el-form-item>
            <el-form-item label="小说状态" prop="serialize">
              <el-radio-group v-model="form.serialize">
                <el-radio :label="1">连载</el-radio>
                <el-radio :label="2">完结</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="上线状态" prop="online">
              <el-radio-group v-model="form.online">
                <el-radio :label="1">上线</el-radio>
                <el-radio :label="2">下线</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="小说简介" prop="introduction">
              <el-input v-model="form.introduction" type="textarea" placeholder="小说简介"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible=false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryParams.pageNo"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="queryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: 'NovelList',
  data() {
    // 自定义验证规则：编辑时如果有原图片则不强制上传
    const validateUrl = (rule, value, callback) => {
      if (this.dialogType === 'add' && !value) {
        callback(new Error('请上传封面图片'));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: false,
      // 选中数组
      selectedIds: [],
      // 总条数
      total: 0,
      // 小说表格数据
      novelList: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      formInline: {
        serialize: '',
        onlineStatus: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入小说名字', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        pname: [
          { required: true, message: '请输入作者名字', trigger: 'blur' }
        ],
        serialize: [
          { required: true, message: '请选择连载状态', trigger: 'change' }
        ],
        introduction: [
          { required: true, message: '请输入小说简介', trigger: 'blur' }
        ],
        url: [
          { validator: validateUrl, trigger: 'change' }
        ],
        online: [
          { required: true, message: '请选择上线状态', trigger: 'change' }
        ]
      },
      dialogVisible: false,
      form: {
        name: '',        // 小说名字
        pname: '',       // 作者名字
        serialize: 1,    // 连载状态，默认连载
        introduction: '', // 小说简介
        url: '',         // 封面图片
        online: 1,       // 上线状态，默认上线
        createtime: ''   // 创建时间
      },
      books: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async Contentsbook(row) {
      // 后续操作可以基于接收到的 row 参数来获取对应小说的相关信息
      await this.bookss(row);
      let a = this.sjss + this.sjs;
      // 模拟异步操作，这里也可以根据真实的异步操作来替换掉setTimeout
      await new Promise((resolve) => setTimeout(() => {
        resolve();
      }, a));
    },

    async bookss(row) {
      let startTimeRequest = Date.now();
      // 假设小说数据行中有个标识小说的唯一id属性名为 novelId，根据实际情况调整
      const res = await axios.post('http://localhost:9999/api-novel/books/findallbyid?pid=' + row.id);
      let endTimeRequest = Date.now();
      let requestTime = endTimeRequest - startTimeRequest;
      console.log("网络请求耗时: " + requestTime);

      this.download = res.data;
      for (var i = 0; i < this.download.length; i++) {
        this.books.push(this.download[i].title + this.download[i].content);
      }

      await this.booksss();

      let endTime = Date.now();
      this.sjs = endTime - startTimeRequest; // 这里修改为从最开始网络请求发起时算总耗时
      console.log("sjs（包含网络请求和后续所有操作）: " + this.sjs);
    },

    booksss() {
      let startTime = Date.now();
      console.log("开始执行下载相关操作");
      let content = '';
      this.books.forEach(chapter => {
        content += chapter;
      });
      try {
        const blob = new Blob([content], {type: 'text/plain;charset=utf-8'});
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = this.novelList.name + '.txt';
        a.click();
        this.books = [];
        let endTime = Date.now();
        this.sjss = endTime - startTime;
        console.log("sjss（下载操作耗时）: " + this.sjss);
      } catch (error) {
        console.error("下载操作失败，错误信息:", error);
        this.$message.error('下载操作出现问题，请检查浏览器设置或稍后重试');
      }
    },

    /** 查询小说列表 */
    getList(){
      this.axios.post(`http://localhost:9999/api-novel/novel/list1?pageNo=${this.queryParams.pageNo}&pageSize=${this.queryParams.pageSize}`, this.formInline).then(res => {
        this.novelList = res.data.data.list;
        this.total = res.data.data.total;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 重置查询表单
      this.formInline = {
        serialize: '',
        onlineStatus: ''
      }
      // 重置分页参数
      this.queryParams = {
        pageNo: 1,
        pageSize: 10
      }
      // 清空选中项（如果有使用表格多选的话）
      if (this.$refs.table) {
        this.$refs.table.clearSelection()
      }
      // 重新加载数据
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.dialogType = 'add'
      this.form = {
        name: '',
        pname: '',
        serialize: 1,
        introduction: '',
        url: '',
        online: 1,
        createtime: new Date().toISOString()
      }
      this.dialogVisible = true
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 格式化时间
          this.form.createtime = this.formatDate(new Date()); // 假设 createtime 是需要格式化的字段
          if (this.dialogType === 'add') {
            this.addNovel(); // 调用添加方法
          } else {
            this.editNovel(); // 调用编辑方法
          }
        }
      });
    },
    /** 格式化日期为 yyyy-MM-dd HH:mm:ss */
    formatDate(date) {
      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
        timeZone: 'Asia/Shanghai', // 设置时区为 GMT+8
      };
      return date.toLocaleString('zh-CN', options).replace(/\//g, '-').replace(' ', ' '); // 替换斜杠为短横线
    },
    /** 添加小说 */
    addNovel(data) {
      const url = 'http://localhost:9999/api-novel/novel/add';
      this.axios.post(url, this.form).then(res => {
        if (res.data) {
          this.$message.success('添加成功');
          this.dialogVisible = false;
          this.getList();
        } else {
          this.$message.error(res.data.msg || '添加失败');
        }
      }).catch(err => {
        console.error(err);
        this.$message.error('添加失败，服务器错误');
      });
    },
    /** 编辑小说 */
    editNovel(data) {
      const url = 'http://localhost:9999/api-novel/novel/add'; // 使用相同的 URL
      this.axios.post(url, this.form).then(res => {
        if (res.data) {
          this.$message.success('修改成功');
          this.dialogVisible = false;
          this.getList();
        } else {
          this.$message.error(res.data.msg || '修改失败');
        }
      }).catch(err => {
        console.error(err);
        this.$message.error('修改失败，服务器错误');
      });
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogVisible = true;
      // 保存原始图片URL
      const originalUrl = row.url;
      this.form = Object.assign({}, row);
      // 如果编辑时没有上传新图片，保留原图片
      if (!this.form.url) {
        this.form.url = originalUrl;
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除小说：' + row.name + '?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        this.axios.post(`http://localhost:9999/api-novel/novel/delete?id=${row.id}`)
            .then(res => {
              if (res.data) {
                this.$message.success('删除成功')
                this.getList() // 刷新列表
              } else {
                this.$message.error(res.data.msg || '删除失败')
              }
            })
            .catch(error => {
              console.error('删除失败:', error)
              this.$message.error('删除失败，服务器错误')
            })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    /** 刷新按钮操作 */
    handleRefresh() {
      this.getList()
    },
    /** 查看小说详情 */
    handleView(row) {
      this.$message.success('查看小说：' + row.title)
    },
    /** 处理上下线操作 */
    handleStatusChange(row, status) {
      const statusText = status === 1 ? '上线' : '下线'
      this.$confirm(`是否确认${statusText}该小说?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 构造请求参数
        const params = {
          id: row.id,
          online: status
        }
        // 调用更新接口
        this.axios.post(`http://localhost:9999/api-novel/novel/updatetwo`, params)
            .then(res => {
              if (res.data) {
                this.$message.success(`${statusText}成功`)
                this.getList() // 刷新列表
              } else {
                this.$message.error(res.data.msg || `${statusText}失败`)
              }
            })
            .catch(error => {
              console.error(`${statusText}失败:`, error)
              this.$message.error(`${statusText}失败，服务器错误`)
            })
      }).catch(() => {
        this.$message.info(`已取消${statusText}`)
      })
    },
    /** 上线操作 */
    handleOnline(row) {
      this.handleStatusChange(row, 1)
    },
    /** 下线操作 */
    handleOffline(row) {
      this.handleStatusChange(row, 2)
    },
    /** 章节列表 */
    handleChapter(row) {
      this.$router.push({path: '/novel/chapter', query: {id: row.id}})
    },
    /** 评论列表 */
    handleComment(row) {
      this.$router.push({path: '/novel/comment', query: {id: row.id}})
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNo = val
      this.getList()
    },

    /** 图片上传成功回调 */
    handleAvatarSuccess(res, file) {
      console.log('上传响应：', res);
      if (res) {
        this.form.url = res;
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败');
      }
    },

    /** 图片上传前的校验 */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style scoped>
.app-container {
  padding: 0;
  background-color: #fff;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.fixed-header {
  position: fixed;
  top: 50px;  /* 与顶部导航栏对齐 */
  left: 210px;  /* 与侧边栏对齐 */
  right: 0;
  background-color: #fff;
  z-index: 999;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.search-bar {
  flex: 1;
}

.toolbar-right {
  margin-left: 20px;
}

.table-container {
  margin-top: 70px;  /* 为固定头部留出空间 */
  padding: 0 20px;
}

.content-container {
  background-color: #fff;
  border-radius: 4px;
  width: 100%;
  overflow-x: hidden;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

.el-table {
  margin-bottom: 20px;
}

.el-link {
  font-size: 12px;
}

/* 添加全局样式，隐藏滚动条但保持滚动功能 */
::-webkit-scrollbar {
  display: none;
}

/* 调整表单项的间距 */
.demo-form-inline .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.demo-form-inline .el-form-item:last-child {
  margin-right: 0;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

/* 添加图片预览悬浮效果 */
.avatar-uploader:hover .avatar {
  opacity: 0.8;
  transition: opacity 0.3s;
}

/* 添加上传区域动画效果 */
.avatar-uploader .el-upload {
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
</style>